#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>              
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>


int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        std::cerr<<"Usage:"<<argv[0]<<" local-port"<<std::endl;
        exit(0);
    }
    uint16_t port=std::stoi(argv[2]);
    std::string serverip=(argv[1]);
    int sockfd=::socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        std::cerr<<"create sock error"<<std::endl;
        exit(1);
    }
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(port);
    ::inet_pton(AF_INET,serverip.c_str(),&server.sin_addr);

    int n=::connect(sockfd,(struct sockaddr*)&server,sizeof(server));
    if(n<0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(2);
    }

    while(true)
    {
        std::string message;
        std::cout<<"please enter :";
        std::getline(std::cin,message);

        write(sockfd,message.c_str(),message.size());
        char inbuff[1024];
        n=read(sockfd,inbuff,sizeof(inbuff));
        if(n>0)
        {
            inbuff[n]=0;
            std::cout<<inbuff<<std::endl;
        }
        else
        {
            break;
        }
    }


    ::close(sockfd);
    return 0;
}